<?php

namespace app\admin\controller;

use app\common\model\ToastType;
use think\Request;
use think\Session;

/**
 * 系统用户
 * @package app\admin\controller
 */
class SysUser extends AdminBaseController
{

    public function login()
    {
        return $this->fetch();
    }

    /**
     * 退出登录
     */
    public function logout() {
        $user = session(SESSION_USER);
        if ($user != null) {
            Session::delete(SESSION_USER);
            $this->redirect('/admin/sysuser/login');
        } else {
            $this->error('非法操作');
        }
    }

    /**
     * 登录
     * @param $username 用户名
     * @param $password 密码
     * @return
     */
    public function doLogin()
    {
        $username = request()->post('username');
        $password = request()->post('password');
        if (empty(trim($username))) {
            $this->showToast(ToastType::WARNING, '用户名不能为空');
            return $this->fetch('login');
        }
        if (empty(trim($password))) {
            $this->showToast(ToastType::WARNING, '密码不能为空');
            return $this->fetch('login');
        }

        $where = ["username" => $username, "password" => md5($password)];

        $user = \app\admin\model\SysUser::where($where)->find();
        if ($user == null) {
            $this->showToast(ToastType::WARNING, '用户名或密码不正确');
            return $this->fetch('login');
        }

        session(SESSION_USER, $user);

        $this->redirect("/admin/index");
    }

    /**
     * 锁屏
     */
    public function lockscreen() {
        $user = $this->getLoginUser();
        $user['lock'] = true;
        session(SESSION_USER, $user);
        return $this->fetch();
    }

    /**
     * 屏幕解锁
     */
    public function unlockscreen() {
        $user = $this->getLoginUser();
        $pwd = request()->post('password');
        if (strcmp($user['password'],md5($pwd)) !== 0) {
            $this->showToast(ToastType::ERROR, '密码不正确');
            return $this->fetch('lockscreen');
        } else {
            $user['lock'] = false;
            session(SESSION_USER, $user);
            $this->redirect('/admin/index');
        }
    }

    /**
     * 用户列表
     * @return \think\Response
     */
    public function index($username = '', $sex = '', $status = '')
    {
        $param = array();
        if (strlen(trim($username)) > 0) {
            $param['username'] = $username;
        }
        if (strlen(trim($sex)) > 0) {
            $param['sex'] = $sex;
        }
        if (strlen(trim($status)) > 0) {
            $param['status'] = $status;
        }
        $list = \app\admin\model\SysUser::where($param)
            ->order("update_time", "desc")
            ->paginate(config('list_rows'), false, array('query' => $param));
        $page = $list->render();
        $this->assign("list", $list);
        $this->assign("page", $page);
        $this->assign('total', $list->total());
        return $this->fetch('list');
    }

    /**
     * 进入创建用户界面
     * @return \think\Response
     */
    public function create()
    {
        return $this->fetch();
    }

    /**
     * 添加用户
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $request->post();
        $result = $this->validate($data,'SysUser');
        if (true !== $result) {
            $this->showToast(ToastType::ERROR, $result);
            return $this->fetch('create');
        }
        $username = $data['username'];
        $user = \app\admin\model\SysUser::where('username', $username)->select();
        if ($user != null) {
            $this->showToast(ToastType::ERROR, '该用户已存在');
            return $this->fetch('create');
        }
        // 上传头像
        $file = $request->file('avatar');
        if ($file != null) {
            $info = $file->validate(['ext' => 'jpg,png,giff,jpeg'])->move(PUBLIC_PATH . UPLOAD_PATH);
            if (!$info) {
                $this->showToast(ToastType::ERROR, $file->getError());
                return $this->fetch('create');
            }
            $avatar = DS . UPLOAD_PATH . DS . $info->getSaveName();
            $data['avatar'] = $avatar;
        }
        $data['password'] = md5($data['password']);
        \app\admin\model\SysUser::create($data);
        $this->showToast(ToastType::SUCCESS, '添加成功');
        $this->redirect("/admin/sysuser");
    }

    /**
     * 查看用户信息
     * @param  int $id 用户ID
     * @return \think\Response
     */
    public function detail($id)
    {
        $user = \app\admin\model\SysUser::get($id);
        if ($user == null) {
            $this->showToast(ToastType::ERROR, '该用户不存在');
            $this->redirect("/admin/sysuser");
        } else {
            $this->assign('sysuser', $user);
            return $this->fetch();
        }
    }

    /**
     * 进入修改用户界面
     * @param  int $id 用户id
     * @return \think\Response
     */
    public function edit($id)
    {
        $user = \app\admin\model\SysUser::get($id);
        if ($user == null) {
            $this->showToast(ToastType::ERROR, '该用户不存在');
            $this->redirect("/admin/sysuser");
        } else {
            $this->assign("sysuser", $user);
            return $this->fetch();
        }
    }

    /**
     * 更新用户信息
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $user = \app\admin\model\SysUser::get($id);
        if ($user == null) {
            $this->showToast(ToastType::ERROR, '无效的用户');
        } else {
            $data = $request->post();
            $result = $this->validate($data,'SysUser.edit');
            if (true !== $result) {
                $this->showToast(ToastType::ERROR, $result);
                $this->redirect("/admin/sysuser/edit/".$id);
                return;
            }
            // 上传新的头像
            $file = $request->file('avatar');
            if ($file != null) {
                // 删除原来的头像
                $avatarPath = PUBLIC_PATH . $user['avatar'];
                if (is_file($avatarPath)) {
                    unlink($avatarPath);
                }
                $info = $file->validate(['ext' => 'jpg,png,giff,jpeg'])->move(PUBLIC_PATH . UPLOAD_PATH);
                if (!$info) {
                    $this->showToast(ToastType::ERROR, $file->getError());
                    return $this->redirect('/admin/sysuser/edit/' . $id);
                }
                $avatar = DS . UPLOAD_PATH . DS . $info->getSaveName();
                $data['avatar'] = $avatar;
            }

            $user->save($data);

            $loginUser = $this->getLoginUser();
            if ($loginUser['id'] == $id) {
                session(SESSION_USER, $user);
            }

            $this->showToast(ToastType::SUCCESS, '修改成功');
        }

        $this->redirect("/admin/sysuser");
    }

    /**
     * 删除一个用户
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $loginUser = $this->getLoginUser();
        if ($loginUser['id'] === $id) {
            $this->showToast(ToastType::ERROR, '兄弟，别想不开~~~');
        } else {
            $user = \app\admin\model\SysUser::get($id);
            if ($user == null) {
                $this->showToast(ToastType::ERROR, '该用户不存在');
            } else {
                $user->delete();
                $this->showToast(ToastType::SUCCESS, '删除成功');
            }
        }
        $this->redirect("/admin/sysuser");
    }

    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('avatar');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if ($info) {
            // 成功上传后 获取上传信息
            // 输出 jpg
            echo $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getSaveName();
            // 输出 42a79759f284b767dfcb2a0197904287.jpg
            echo $info->getFilename();
        } else {
            // 上传失败获取错误信息
            echo $file->getError();
        }
    }

    /**
     * 重置密码
     */
    public function resetpwd($id)
    {
        $user = \app\admin\model\SysUser::get($id);
        if ($user == null) {
            $this->showToast(ToastType::ERROR, '无效的用户');
        } else {
            $user['password'] = md5(DEFAULT_PWD);
            $user->save();
            $this->showToast(ToastType::SUCCESS, '密码重置成功');
        }
        $this->redirect('/admin/sysuser');
    }
}
